package com.imooc.ecommerce.filter;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * HTTP 请求头部携带 token验证过滤器
 * @author zhangshao
 * @date 2023/11/24 22:33
 */
public class HeadTokenGatewayFilter implements GatewayFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 从Http Header中寻找key为token value为imooc的键值对
        String name = exchange.getRequest().getHeaders().getFirst("token");
        if("imooc".equals(name)){
            return chain.filter(exchange);
        }

        //标记此次请求没有权限,并结束这次请求
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        return exchange.getResponse().setComplete();
    }

    /**
     * 数字越大，优先级越低
     * @return 优先级level
     */
    @Override
    public int getOrder() {
        return HIGHEST_PRECEDENCE+2;
    }
}
